#include "StdAfx.h"
#include "DrumFactory.h"
#include "audio\DirSoundSource.h"


CDrumFactory::CDrumFactory(void)
{
	LoadFile(L"./sounds/drumriff.wav");
	mNextInstrument = Synth;
}


CDrumFactory::~CDrumFactory(void)
{
}

CInstrument *CDrumFactory::CreateInstrument( void )
{
	switch (mNextInstrument)
	{
	case Wave: 
		return CreateWaveInstrument();
		break;
	case Synth:
		return CreateSynthInstrument();
		break;
	default:
		break;
	}
}

CDrumInstrument *CDrumFactory::CreateSynthInstrument( void )
{
	CDrumInstrument *lInstrument = new CDrumInstrument();

	return lInstrument;
}

CWaveInstrument *CDrumFactory::CreateWaveInstrument( void )
{
	// Synth is the default value
	mNextInstrument = Synth;
	CWaveInstrument *lInstrument = new CWaveInstrument();
	lInstrument->GetPlayer()->SetSamples( &mWaveMap[mNextFileName].at(0), (unsigned)mWaveMap[mNextFileName].size() );

	return lInstrument;
}

void CDrumFactory::SetNote( CNote *aNote )
{
	// Get a list of all attribute nodes and the
    // length of that list
    CComPtr<IXMLDOMNamedNodeMap> attributes;
    aNote->Node()->get_attributes(&attributes);
    long len;
    attributes->get_length(&len);

    // Loop over the list of attributes
    for(int i=0;  i<len;  i++)
    {
        // Get attribute i
        CComPtr<IXMLDOMNode> attrib;
        attributes->get_item(i, &attrib);

        // Get the name of the attribute
        CComBSTR name;
        attrib->get_nodeName(&name);

        CComVariant value;
        attrib->get_nodeValue(&value);

		if( name == "file" )
		{
			mNextInstrument = Wave;
			LoadFile(value.bstrVal);
			mNextFileName = value.bstrVal;
		}
    }
}

bool CDrumFactory::LoadFile( const WCHAR *aFileName )
{	
	CDirSoundSource mFile;

	//Check to see if the wav file is already stored in memory
	if( !mWaveMap[aFileName].empty() )
	{
		return true;
	}
	if( !mFile.Open( aFileName ) )
	{
		CString lMsg = L"Unable to open audio file";
        lMsg += aFileName;
        AfxMessageBox(lMsg);
        return false;
    }

    for(int i=0;  i<mFile.NumSampleFrames();  i++)
    {
        short frame[2];
        mFile.ReadFrame(frame);
        mWaveMap[aFileName].push_back(frame[0]);
    }

    mFile.Close();
    return true;
}